package com.example.demo_aidl_client

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.demo_aidl_server.IMyAidlInterface

/***
 * 1.aidl实现流程
 * 服务端：创建aidl文件并编辑提供方法–》rebuild—>创建服务，onbind方法中返回一个binder对象—》清单文件注册服务
 * 客户端：创建aidl文件和服务端一模一样–》rebuild–〉绑定服务调用方法
 *
 * 2.oneway关键字：表示该方法为异步方法，执行耗时操作。
 *
 * 3.参数关键字：in out inout
 *   oneway void sumAsync(in int num1,out int num2);
 * in：输入参数，客户端流向服务端，服务端不能修改参数
 * out：输出参数，服务端流向客户端，服务端修改值，忽略客户端初始值
 * inout：是输入参数也是输出参数，客户端传递数据服务端，服务端修改值后并返回客户端
 */
class MainActivity : AppCompatActivity() {
    private lateinit var intent:Intent
    private var carService:IMyAidlInterface? = null

    private var handler:Handler = object :Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            Log.d("TAG","异步计算结果：${msg.obj}")
        }
    }
    private val conn = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.d("TAG","onServiceConnected")
            carService = IMyAidlInterface.Stub.asInterface(service)
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Log.d("TAG","onServiceDisconnected")
        }

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        //绑定服务
        intent = Intent()
        intent.setAction("com.demo.car")
        intent.setPackage("com.example.demo_aidl_server")
        bindService(intent,conn,BIND_AUTO_CREATE)
    }
    //解除绑定
    override fun onDestroy() {
        super.onDestroy()
        unbindService(conn)
    }

    fun sum(view: View) {
        //调用远程服务的sum方法
        val sum = carService?.sum(2, 5)
        Log.d("TAG", "同步计算:$sum ")

    }

    fun sum2(view: View) {
        carService?.sum(2, 5)
        Log.d("TAG", "异步计算:结果接口回调 ")
    }
}